//
//  body.cpp
//  template4
//
//  Created by Xiaochen Lian on 5/15/12.
//  Copyright (c) 2012 University of California, Los Angeles. All rights reserved.
//

#include "body.h"
#include "limb.h"

CBody::CBody(vec3 scale, vec4 pos) 
{
    m_type = BODY;
    m_scale = scale;
    set_pos(pos);
    m_tfm = mat4(1.0);
    LEVEL = 5;
}

inline void CBody::set_material(const lighting_struct &material)
{
    m_material = material;
}

void CBody::build_model(const point4 &parent_mass_center)
{
    m_model_mat = Translate(m_model_pos);
    m_scale_mat = Scale(m_scale);
    
    m_material.ambient = color4( 0.8f, 0.8f, 0.8f, 1.0f );
    m_material.diffuse = color4( 0.8f, 0.8f, 0.8f, 1.0f );
    m_material.specular = color4( 0.1f, 0.1f, 0.1f, 1.0f );
    m_material.shininess = 10.0f;
    
    m_mass_center = m_model_mat * parent_mass_center;
}


void CBody::draw(const mat4 &tfm_parent)
{
    // set shader variables
    glUniform4fv(uAmbient, 1, g_env_lighting.ambient * m_material.ambient);
    glUniform4fv(uDiffuse, 1, g_env_lighting.diffuse.x * m_material.diffuse);
    glUniform4fv(uSpecular, 1, g_env_lighting.specular * m_material.specular);
    glUniform1f(uShininess, g_env_lighting.shininess * m_material.shininess);
    // draw objects
    mat4 m = tfm_parent * m_model_mat * m_tfm;
//    m_mass_center = m*vec4(0.0, 0.0, 0.0, 1.0);
    drawEllips(m * m_scale_mat);

    for (int i = 0; i < m_children.size(); ++i)
        m_children[i]->draw(m);
}

void CBody::draw_axis(const mat4 &tfm_parent)
{
    drawAxis(tfm_parent * m_model_mat * m_tfm * m_scale_mat);
}

pair<vec4, vec4> CBody::aerodynamics(const bird_status &nstatus, const mat4 &tfm, const double timestep)
{
    vec4 force = 0.0;
    vec4 torque = 0.0;
    pair<vec4, vec4> p;
    
    for (int i = 0; i < m_children.size(); ++i)
    {
        p = m_children[i]->aerodynamics(nstatus, tfm, timestep);
        force += p.first;
        torque += p.second;
    }
    
    return pair<vec4, vec4>(force, torque);
}

void CBody::update(const bird_status &cstatus, const mat4 tfm_parent)
{
    m_tfm = Translate(cstatus.pos);
    m_mass_center = tfm_parent * m_model_mat * m_tfm * vec4(0.0, 0.0, 0.0, 1.0);
    
    for (int i = 0; i < m_children.size(); ++i)
        m_children[i]->update(cstatus, mat4(1.0));
}